import { defineStore } from 'pinia'
import { ref ,computed} from 'vue'
import { getllmv2, getSubject } from '@/api'

import { BASE_URL } from '@/utils/axios'

const handleRes = (text: string) => {
  const res: any = text.split('\n').filter(Boolean).map(JSON.parse as any) 
  
 return  res.map((item:any) => item.choices.map((d:any) => d.delta.content).join('')).join('')
}

// 生成随机32位id 包含字母数字
const generateRandomString = (length: number) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
 return result
}
export const useUsetStore = defineStore(
  'user',
  () => {
    const currentId = ref<string>(generateRandomString(32))
    const currentQA = ref<any[]>([])
    const subjectList = ref<{infoId:string,id:string}[]>([])
    const loading = ref(false)
    const images = ref<string[]>([])
    const inputValue = ref('')
    const img = ref('')
    const content = ref('')
    const subject = ref('')
    const messageContent = ref('')

    const isNewChat = computed(() => !subjectList.value.find((item: any) => item.infoId === currentId.value))

    // 新建对话
    const newChat = () => {
      inputValue.value = ''
      currentQA.value = []
      currentId.value = generateRandomString(32)
      images.value = []
    }

    const setInputValue = (value: string) => {
      inputValue.value = value
    }

    const setCurrentId = async (id: string) => {
      const store = useUsetStore()
      store.clearImages()
      inputValue.value = ''
      currentId.value = id
      const res = await getSubject({ "method": "history", id })
      currentQA.value = res
    }

    const setImages = (url:string,index?:number) => {
      if (typeof index === 'undefined') images.value.push(url)
      else images.value.splice(index, 1, url)
    }
    const clearImages = () => {
      images.value = []
    }

    const deleteImg = (index:number) => {
      images.value.splice(index, 1)
    }

    const getSubjectList = async () => { 
      const res = await getSubject({ "method": "get", })  
      subjectList.value = res  
    }
    const getData = async (value: string) => {
     
      content.value = value
      
      currentQA.value.push({
        role: 'user',
        content: [...images.value.map(url => ({type:'image_url',image_url:{url}})),{type:'text', text: value }],
      })
      // 返回结果是流式数据 需要手动拼接
      loading.value = true
      let result = '' 
      const sub = currentId.value
      const response  = await fetch(BASE_URL + '/api/llmv2', {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream',
          'Cache-Control': 'no-cache',
        },
        body: JSON.stringify({
          content: content.value,
          subject: currentId.value,
          img: images.value.join(','),
        }),
      }) 
      
      const reader = response!.body!.getReader();
      const decoder = new TextDecoder('utf-8'); 
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        const text = decoder.decode(value, { stream: true });
        result += text; 
      } 
      
      messageContent.value = handleRes(result)
     
      if(sub === currentId.value) currentQA.value.push({
        role: 'assistant',
        content:  messageContent.value,
      }) 
      console.log('结束');
      
      loading.value = false

      const subject = subjectList.value.find((item: any) => item.infoId === currentId.value)
      if (!subject) getSubjectList()
      return result
    }
    return {
      loading,
      img,
      content,
      subject,
      getData,
      getSubjectList,
      subjectList,
      setCurrentId,
      currentId,
      currentQA,
      images,
      setImages,
      clearImages,
      newChat,
      setInputValue,
      inputValue,
      messageContent,
      deleteImg,
      isNewChat,
    }
  },
  {
    persist: true,
  },
)
